<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/11
 * Time: 17:35
 */

namespace App\Service;

use App\Models\Role;
use App\Models\Permission;
use Illuminate\Support\Facades\DB;

class RoleService
{
    /**
     * 获取角色列表
     * @param array $params
     * @param string $orderBy
     * @param string $sort
     * @param int $page
     * @param int $limit
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getList($params = [],$orderBy = 'id',$sort = 'DESC',$page = 1,$limit = 10)
    {
        $where = [];
//        $roleModel = new Role();
        if(isset($params['name']) && empty($params['name'])){
            $where[] = ['name','like',"%{$params['name']}%"];
        }
        $start=($page-1)*$limit;
        $list = Role::with(['permissions'])->where($where)->skip($start)->take($limit)->orderBy($orderBy,$sort)->get()->toArray();
        $count = Role::where($where)->count();
        $pageCount = ceil($count/$limit);
        $data = [
            'list'          => $list,
            'pageCount'     => $pageCount,
        ];
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * 通过ID获取用户角色信息
     * @param int $roleId
     * @return array
     */
    public static function getRoleById($roleId = 0)
    {
        $info = Role::with(['permissions'])->where('id', $roleId)->first(['id', 'name', 'slug', 'created_at', 'updated_at']);
        $info = $info ? $info->toArray() : [];
        return Response()->json(['code' => 200, 'msg' => '获取成功', 'data' => $info]);
    }

    /**
     * 添加
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function add($params = [])
    {
        try{
            if(Role::where('slug',trim($params['slug']))->first()){
                throw new \Exception('该角色标识已存在');
            }
            $info = Role::create(['name'=>trim($params['name']),'slug'=>trim($params['slug'])]);
            if(!$info){
                throw new \Exception('新增角色失败');
            }
            if(isset($params['permission_ids']) && !empty($params['permission_ids'])){
                $insertData = [];
                $roleIdArr = is_array($params['permission_ids']) ? $params['permission_ids'] : [$params['permission_ids']];
                foreach($roleIdArr as $v){
                    $insertData[] = [
                        'role_id'   => $info->id,
                        'permission_id'   => $v,
                        'created_at'    => date('Y-m-d H:i:s'),
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ];
                }
                DB::table('admin_role_permissions')->insert($insertData);
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }

        return Response()->json(['code'=>200,'msg'=>'添加角色成功']);
    }

    /**
     * 修改
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function edit($params = [])
    {
        try{
            $info = Role::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('该角色不存在');
            }
            if(Role::where('slug',trim($params['slug']))->where('id','!=',intval($params['id']))->first()){
                throw new \Exception('该角色标识已存在');
            }

            $info->name     = trim($params['name']);
            $info->slug = trim($params['slug']);
            $save = $info->save();
            if(!$save){
                throw new \Exception('修改失败');
            }
            $idArr = DB::table('admin_role_permissions')->where('role_id',$info->id)->pluck('permission_id');
            $idArr = $idArr ? $idArr->toArray() : [];
            if(!empty($params['permission_ids'])){
                $permissionIdArr = is_array($params['permission_ids']) ? $params['permission_ids'] : [$params['permission_ids']];
                foreach($permissionIdArr as $v){
                    if(!empty($idArr) && in_array($v,$idArr)){
                        unset($idArr[array_search($v,$idArr)]);
                    }else{
                        DB::table('admin_role_permissions')->insert(['permission_id'=>$v,'role_id'=>$info->id,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
                    }
                }
            }
            if(!empty($idArr)){
                DB::table('admin_role_permissions')->where('role_id',$info->id)->whereIn('permission_id',$idArr)->delete();
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'修改成功']);
    }

    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public static function destroy($id)
    {
        $idArr = is_array($id) ? $id : [$id];
        if(!$idArr){
            return Response()->json(['code'=>201,'msg'=>'请选择要删除的角色']);
        }
        if(in_array(1,$idArr)){
            return Response()->json(['code'=>201,'msg'=>'角色存在超级管理员角色，不支持删除']);
        }
        $del = Role::destroy($idArr);
        if(!$del){
            return Response()->json(['code'=>201,'msg'=>'删除失败']);
        }
        DB::table('admin_role_permissions')->whereIn('role_id',$idArr)->delete();
        return Response()->json(['code'=>200,'msg'=>'删除成功']);


    }

}
